<template>
  <div>
    <!-- 表头 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域  组件 -->
      <el-alert
        show-icon
        :closable="false"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
      >
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat-opt">
        <el-col>
          <span>选择商品分类</span>
          <!-- 选择商品分类的级联选择框 -->
          <!-- 指定hover时触发子菜单 
          :options 指定数据源 
          cateList 数据体
          -->
          <el-cascader
            expand-trigger="hover"
            :options="cateList"
            class="cascader"
            :props="cateProps"
            v-model="selectesCateKeys"
            @change="handleChage"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 动态参数 -->
          <el-button
            :disabled="isBtnDisable"
            type="primary"
            size="mini"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <el-table :data="manyTableDate" border stripe>
              <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环tag标签 -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 动态变化  输入文本框-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputVal"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <!-- 插槽 -->
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParmas(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 静态属性 -->
          <el-button
            :disabled="isBtnDisable"
            type="primary"
            size="mini"
            @click="addDialogVisible = true"
            >添加属性</el-button >
            <el-table :data="onlyTableDate" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputVal"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParmas(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加参数对话框 -->
      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <el-form
          label-width="80px"
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- <el-input label=""></el-input> -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParms">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改对话框 -->
      <el-dialog
        :title="'修改' + titleText"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form
          label-width="80px"
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- <el-input label=""></el-input> -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // cascader 绑定数据 商品分类列表
      cateList: [],
      // 级联选择框的配置对象
      cateProps: {
        value: "cat_id",        //指定的id值
        label: "cat_name",      //看见的值  名称
        children: "children",   //父子的嵌套属性
      },
      //级联选择框双向绑定的数组
      selectesCateKeys: [],

      // 通过many或者only获取菜单数据  被激活的页签名称
      activeName: "many",
      //动态参数
      manyTableDate: [],
      //静态参数
      onlyTableDate: [],

      //控制弹出框
      addDialogVisible: false,
      addForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入添加内容!", trigger: "blur" },
        ],
      },

      //控制修改对话框
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入添加内容!", trigger: "blur" },
        ],
      },
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // getCateList获取所有的商品 cascader 相关操作 分类
    async getCateList() {
      const { data: res } = await this.$http.get("categories")
      if (res.meta.status !== 200) {
        return this.$message.error("请求商品数据失败！")
      }
      this.cateList = res.data                  //赋值数据
      // console.log(this.cateList,'你好')
    },
    //级联选择框选中项变化，会触发这个函数
    handleChage() { // 处理函数
      // console.log(this.selectesCateKeys,'你好-2'); 列表数据
      this.getParamsDate()
    },
    // 获取参数的列表数据 （回点函数：根据activeName选择性获取数据）
    async getParamsDate() {
      if (this.selectesCateKeys.length !== 3) {
        this.selectesCateKeys = []
        this.manyTableDate=[] //二级分类清空
        this.onlyTableDate=[]
        return
      }
      //证明选择了三级分类
      //  console.log(this.selectesCateKeys)
      //根据所选id，和当前所处的面板，获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cated}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败！")
      }
      // console.log(res.data,'胖胖');
      //遍历成为数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals
          ? (item.attr_vals = item.attr_vals.split(","))
          : []
        //控制文本框的显示与隐藏
        item.inputVisible = false
        //文本框中输入的值
        item.inputVal = ""
      })
      console.log(res.data)
      //根据activeName选择性获取数据
      if (this.activeName === "many") {
        this.manyTableDate = res.data
      } else {
        this.onlyTableDate = res.data
      }
    },
    // tab页点击事件的处理函数 点击事件
    handleTabClick() {
      // console.log(this.activeName)
      //回点函数
      this.getParamsDate()
    },
    //弹出框刷新  监听添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //添加参数到后台数据
    async addParms() {
      const { data: res } = await this.$http.post(
        `categories/${this.cated}/attributes`,
        {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName,
        }
      )
      if (res.meta.status !== 201) {
        return this.$message.error("添加参数失败！")
      }
      this.$message.success("添加参数成功！")
      this.getParamsDate()  //刷新
      this.addDialogVisible = false //关闭的对话框
    },
    //点击弹出修改对话框
    async showEditDialog(attr_id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cated}/attributes/${attr_id}`,
        {
          params: { attr_sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数信息失败")
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    //点击按钮，修改参数信息传到后台数据，并再次渲染
    editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cated}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) {
          this.$message.error("获取参数信息失败！")
        }
        this.$message.success("修改成功！")
        this.getParamsDate()
        this.editDialogVisible = false
      })
    },

    //删除数据 根据id删除对应数据
    async removeParmas(attr_id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err)
      //用户取消了删除的操作
      if (confirmResult !== "confirm") {
        return this.$message.info("用户已取消删除参数")
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cated}/attributes/${attr_id}`
      )
      if (res.meta.status != 200) {
        return this.$message.error("删除失败！")
      }
      this.$message.success("修改成功")
      this.getParamsDate()
    },
    // tag动态
    handleInputConfirm(row) {
      if (row.inputVal.trim().length === 0) {
        row.inputVal = ""
        row.inputVisible = false //为false就可以隐藏文本框
        return
      }
      //如果没有return,则证明需要数据传递
      row.attr_vals.push(row.inputVal.trim())
      row.inputVal = ""
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    //点击按钮,展示文本输入框
    showInput(row) {
      row.inputVisible = true
      //让文本框自动获得焦点
      //nextTick 当页面上页面元素被重新渲染上后才会执行回调函数的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除参数对应的参数可选项
    handleClose(i, row) {
      console.log(row.attr_vals);
      row.attr_vals.splice(i,1) //删除一项
      this.saveAttrVals(row)
    },
    //将attr_vals的操作保存到数据库
    async saveAttrVals(row) {
      //发起请求,保存数据
      const { data: res } = await this.$http.put(
        `categories/${this.cated}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(","),
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error("修改参数失败")
      }
      this.$message.success("修改参数成功")
    },
  },
  computed: {//计算属性
    //如果按钮需要被禁用，则返回true，反之false 
    isBtnDisable() {
      if (this.selectesCateKeys.length !== 3) {
        return true
      }
      return false
    },
    //当前选中的三级分类的id
    cated() {
      //获取id值，
      if (this.selectesCateKeys.length === 3) {
        return this.selectesCateKeys[2]
      }
      return null
    },
    //动态得到弹出框
    titleText() {
      if (this.activeName === "many") {
        return "动态参数"
      }
      return "静态属性"
    },
  },
}
</script>

<style lang="less" scoped>
.cat-opt {
  margin: 15px 0;
}
.cascader {
  margin-left: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>